# Database Adopter
#
#
#
#===========================================================================
import dbi
import odbc
from datetime import datetime

gicu_db = "GICU/hps/notroot"
nsicu_db = "NSICU/hps/notroot"
cicu_db = "CICU/hps/notroot"
ism_db = "ism/ism/ism4u"

def toGICU(query, n=1):
    db = None
    c = None
    r = []
    db = odbc.odbc(gicu_db)
    time1 = datetime.now()
    c = db.cursor()
    c.execute(query)
    result = c.fetchall()
    time2 = datetime.now()
    duration = time2 - time1
    print str(duration) + " time spent on execute query (" + query + ")\n"

    if n == 1:
        for n in range(0, len(result)):
            r.append(result[n][0])
        return r
    elif n == 2:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1])
            r.append(current)
        return r
    elif n == 3:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1]) + ';' + str(result[n][2])
            r.append(current)
        return r
    elif n == 4:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1]) + ';' + str(result[n][2]) + ';' + str(result[n][3])
            r.append(current)
        return r

def toNSICU(query):
    db = None
    c = None
    r = []
    db = odbc.odbc(nsicu_db)
    c = db.cursor()
    c.execute(query)
    result = c.fetchall()
    for n in range(0, len(result)):
        r.append(result[n][0])
    return r

def toCICU(query):
    db = None
    c = None
    r = []
    db = odbc.odbc(cicu_db)
    c = db.cursor()
    c.execute(query)
    result = c.fetchall()
    for n in range(0, len(result)):
        r.append(result[n][0])
    return r

# make connection with the archival db and execute query
# n refers to the number of variables to be retrieved (default is 1)
def toISM(query, n=1):
    db = None
    c = None
    r = []
    db = odbc.odbc(ism_db)
    c = db.cursor()
    c.execute(query)
    result = c.fetchall()

    if n == 1:
        for n in range(0, len(result)):
            r.append(result[n][0])
        return r
    elif n == 2:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1])
            r.append(current)
        return r
    elif n == 3:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1]) + ';' + str(result[n][2])
            r.append(current)
        return r
    elif n == 4:
        for n in range(0, len(result)):
            current = str(result[n][0]) + ';' + str(result[n][1]) + ';' + str(result[n][2]) + ';' + str(result[n][3])
            r.append(current)
        return r

